package com.atguigu.pojo;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Printers {

    //设置状态位
    private String status = "A";

    private final Lock lock = new ReentrantLock();

    //设置状态锁
    private final Condition conditionA = lock.newCondition();
    private final Condition conditionB = lock.newCondition();
    private final Condition conditionC = lock.newCondition();

    public void printA(){
        //上锁
        lock.lock();
        try{
            //判断
            while(status!="A"){
                conditionA.await();
            }
            //干活
            for(int i=1; i<=5; i++){
                System.out.println(Thread.currentThread().getName()+" "+i);
            }
            //转换状态
            status="B";
            //通知
            conditionB.signal();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }

    }

    public void printB(){
        //上锁
        lock.lock();
        try{
            //判断
            while(status!="B"){
                conditionB.await();
            }
            //干活
            for(int i=1; i<=10; i++){
                System.out.println(Thread.currentThread().getName()+" "+i);
            }
            //转换状态
            status="C";
            //通知
            conditionC.signal();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }

    }

    public void printC(){
        //上锁
        lock.lock();
        try{
            //判断
            while(status!="C"){
                conditionC.await();
            }
            //干活
            for(int i=1; i<=15; i++){
                System.out.println(Thread.currentThread().getName()+" "+i);
            }
            //转换状态
            status="A";
            //通知
            conditionA.signal();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }

    }

}
